package com.neusoft.chatserver.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.neusoft.chatserver.dto.MessageQuery;
import com.neusoft.chatserver.dto.RespBean;
import com.neusoft.chatserver.entity.Message;
import com.neusoft.chatserver.mapper.MessageMapper;
import com.neusoft.chatserver.service.IMessageService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author liuxp
 * @since 2021-07-14
 */
@Service
public class MessageServiceImpl extends ServiceImpl<MessageMapper, Message> implements IMessageService {
    @Autowired
    MessageMapper messageMapper;
    @Override
    public void addMessage(Message message) {
        messageMapper.insert(message);
    }

    @Override
    public   List<Message> getTodayMessage(MessageQuery messageQuery) {

        LambdaQueryWrapper<Message> wrapper = Wrappers.lambdaQuery();
        Date d = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String sdate = sdf.format(d);
        sdate = sdate.substring(0, 10);
        if(messageQuery.getGroup() != null){
            // 群聊的消息统一全部返回
            wrapper.eq(Message::getMsgGroupId, messageQuery.getGroup());
            wrapper.likeRight(Message::getMsgTime,  sdate);
        }else{
            //从from 发给 to的
            wrapper.eq(Message::getMsgFrom, messageQuery.getFrom());
            wrapper.eq(Message::getMsgTo, messageQuery.getTo());
            wrapper.likeRight(Message::getMsgTime,  sdate);
            String finalSdate = sdate;
            wrapper.or(newwrapper -> newwrapper
                    .eq(Message::getMsgFrom, messageQuery.getTo())
                    .eq(Message::getMsgTo, messageQuery.getFrom())
                    .likeRight(Message::getMsgTime, finalSdate));
        }
        List<Message> messageList = messageMapper.selectList(wrapper);
        return messageList;
    }
}
